# Replication archive for 
# Coppock, Alexander, Donald P. Green, and Ethan Porter. 2022. 
# Does Digital Advertising Affect Vote Choice? Evidence from a Randomized Field Experiment 
# Research & Politics. 

rm(list = ls())
# setwd() to replication archive

library(tidyverse)
library(estimatr)
library(texreg)

precinct_level <- read_rds("CGP_2022_precinct_level.rds")
zip_code_level <- read_rds("CGP_2022_zip_code_level.rds")

precinct_balance <-
  lm_robust(
    Z ~ dem_two_party_vote_margin_2016_nona + vote_2016_missing +
      dem_two_party_vote_margin_2014_nona + vote_2014_missing +
      dem_two_party_vote_margin_2012_nona + vote_2012_missing,
    clusters = vb_tsmart_zip,
    data = precinct_level
  )

# reports relevant F-test
glance(precinct_balance)

texreg(
  precinct_balance,
  custom.coef.names = c(
    "Intercept",
    "Two Party Vote Share (2016)",
    "Missingness Indicator (2016)",
    "Two Party Vote Share (2014)",
    "Missingness Indicator (2014)",
    "Two Party Vote Share (2012)",
    "Missingness Indicator (2012)"
  ),
  digits = 3,
  stars = 0.05,
  custom.note = "%stars. CR2 Cluster-robust standard errors are in parentheses.",
  include.ci = FALSE,
  include.adjrs = FALSE,
  include.rmse = FALSE,
  dcolumn = TRUE,
  booktabs = TRUE,
  use.packages = FALSE,
  table = FALSE,
  # file = "../output_for_overleaf/florida_balance.tex"
)

# at the zip code level -------------------------------------

zip_balance <-
  lm_robust(
    Z ~ dem_two_party_vote_margin_2016_nona +
      dem_two_party_vote_margin_2014_nona +
      dem_two_party_vote_margin_2012_nona,
    data = zip_code_level
  )

# reports relevant F-test
glance(zip_balance)

# check names
texreg(zip_balance)

texreg(
  zip_balance,
  custom.coef.names = c(
    "Intercept",
    "Two Party Vote Share (2016)",
    "Two Party Vote Share (2014)",
    "Two Party Vote Share (2012)"
  ),
  digits = 3,
  stars = 0.05,
  custom.note = "%stars. HC2 Cluster-robust standard errors are in parentheses.",
  include.ci = FALSE,
  include.adjrs = FALSE,
  include.rmse = FALSE,
  dcolumn = TRUE,
  booktabs = TRUE,
  use.packages = FALSE,
  table = FALSE,
  # file = "../output_for_overleaf/florida_balance_zip_level.tex"
)


# attrition check ---------------------------------------------------

with(precinct_level, prop.table(table(treatment, vote_2018_missing), margin = 1))

attrition_check1 <- lm_robust(vote_2018_missing ~ treatment, cluster = vb_tsmart_zip, data = precinct_level)
attrition_check2 <- lm_robust(vote_2018_missing ~ Z, cluster = vb_tsmart_zip, data = precinct_level)

tidy(attrition_check1)
tidy(attrition_check2)
glance(attrition_check1)
glance(attrition_check2)


